package com.apes.fn.scm.crossCompany.transfer.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.crossCompany.transfer.model.PrintRecord;
import com.apes.fn.scm.crossCompany.transfer.repository.PrintRecordRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.metadata.BusinessType;
import com.apes.framework.plugin.soe.store.database.repository.BusinessTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.crossCompany.transfer.service
 * @ClassName: printRecordService
 * @Author: ljp
 * @CreateTime: 2021-07-23 14:00
 * @Description: 打印记录
 * @Version: 1.0
 */
@Service("printRecordService")
public class PrintRecordService extends DomainService {

    @Autowired
    private PrintRecordRepository printRecordRepository;

    /**
     * 记录单据打印次数
     * @param request
     */
    public void setPrintRecordNumber(SimpleRequest request) {
        JSONObject model = request.getJO();
        String id = model.getString("id");
        if (!"".equals(id)) {
            PrintRecord printRecord = printRecordRepository.findBySource(model.getString("id"));
            if (printRecord != null) {
                printRecord.setPrintNumber(printRecord.getPrintNumber() + 1);
                printRecordRepository.saveAndFlush(printRecord);
            }else {
                PrintRecord printRecordNew = new PrintRecord();
                printRecordNew.setSource(model.getString("id"));
                printRecordNew.setSourceBusinessType(model.getString("innerBusinessType"));
                BusinessType businessType = SpringManager.getBean(BusinessTypeRepository.class).findOne(model.getString("innerBusinessType"));
                printRecordNew.setSourceBusinessTypeName(businessType.getName());
                printRecordNew.setPrintNumber(1);
                printRecordRepository.saveAndFlush(printRecordNew);
            }
        }
    }

    public double findOne(SimpleRequest request) {
        String id = request.getJO().getString("id");
        PrintRecord printRecord = printRecordRepository.findBySource(id);
        if (printRecord == null) {
            return 0;
        }else {
            return printRecord.getPrintNumber();
        }
    }
}
